#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#define MAX_CMD_STR 100

int echo_rqt(int sockfd){
    char buf[MAX_CMD_STR];
    int res;
    while(fgets(buf, MAX_CMD_STR + 1, stdin)){
        if (strncmp(buf, "exit", 4) == 0)
            return 0;
        int len_h = strnlen(buf, MAX_CMD_STR);
        buf[len_h - 1] = '\0';
        int len_n = htonl(len_h);
        res = write(sockfd, &len_n, sizeof(len_n));
        if (res < 0) {
            printf("[cli] write len return %d and errno is %d\n", res, errno);
            if (errno == EINTR)
                continue;
            return 0;
        }
        res = write(sockfd, buf, len_h);
        if (res < 0) {
            printf("[cli] write data return %d and errno is %d\n", res, errno);
            if (errno == EINTR)
                continue;
            return 0;
        }
        int sum = 0;
        res = read(sockfd, &len_n, sizeof(len_n));
        len_h = ntohl(len_n);
        if (res < 0) {
            printf("[cli] read len return %d and errno is %d\n", res, errno);
            if (errno == EINTR)
                continue;
            return 0;
        }
        while(sum != len_h) {
            res = read(sockfd, buf + sum, len_h);
            if (res < 0) {
                printf("[cli] read data return %d and errno is %d\n", res, errno);
                if (errno == EINTR)
                    continue;
                return 0;
            }
            sum += res;
        }
        printf("[echo_rep] %s\n", buf);
    }
    return 0;
}

int main(int argc, char *argv[]) {
    int res;
    struct sockaddr_in srv_addr;
    int connfd;

    if (argc != 3){
        printf("Usage:%s <IP> <PORT>\n", argv[0]);
        return 0;
    }
    memset(&srv_addr, 0, sizeof(srv_addr));
    srv_addr.sin_family = AF_INET;
    inet_pton(AF_INET, argv[1], &srv_addr.sin_addr.s_addr);
    srv_addr.sin_port = htons(atoi(argv[2]));

    connfd = socket(AF_INET, SOCK_STREAM, 0);
    do {
        res = connect(connfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
        if (res == 0){
            printf("[cli] server[%s:%s] is connected!\n", argv[1], argv[2]);
            if (echo_rqt(connfd) == 0)
                break;
        } else if (res == -1 && errno == EINTR)
            continue;
    }while (1);
    close(connfd);
    printf("[cli] connfd is closed!\n");
    printf("[cli] client is exiting!\n");

    return 0;
}
